<template>
	<view class="container">
		<swiper class="video-swiper" :class="{'comments-open': commentsOpen}" vertical :circular="false" @change="onSwiperChange">
			<swiper-item v-for="(video, index) in videoList" :key="index">
				<view class="video-container" :class="video.type === '16:9' ? 'video-wide' : 'video-tall'">
					<video 
						:src="video.url" 
						:poster="video.cover"
						class="video-player"
						:controls="false"
						:autoplay="currentIndex === index"
						@click="togglePlay"
						@loadedmetadata="onVideoLoaded"
						@waiting="onVideoWaiting"
						@error="onVideoError"
						@ended="onVideoEnd"
						@timeupdate="onVideoTimeUpdate"
						:id="'video-' + index"
						:data-index="index"
					></video>
					
					<!-- 加载进度条 -->
					<view class="loading-container" v-if="video.loading && !video.canPlay">
						<view class="loading-circle"></view>
					</view>
					
					<!-- 无视频提示 -->
					<view class="no-video" v-if="!video.url">
						<text class="no-video-text">没有视频了哦，请检查网络</text>
					</view>
					
					<view class="video-info">
						<view class="user-info">
							<image class="avatar" :src="video.avatar" mode="aspectFill"></image>
							<view class="user-details">
								<text class="username">{{video.username}}</text>
								<text class="description">{{video.description}}</text>
							</view>
							<view class="follow-btn" @click="toggleFollow(video)">
								<text :class="['follow-text', video.isFollowed ? 'followed' : '']">
									{{video.isFollowed ? '已关注' : '关注'}}
								</text>
							</view>
						</view>
					</view>
					
					<!-- 进度条 -->
					<view class="progress-container">
						<view class="progress-bar" 
							@touchstart="onProgressTouchStart"
							@touchmove="onProgressTouchMove"
							@touchend="onProgressTouchEnd"
						>
							<view class="progress-inner" :style="{width: (video.progress || 0) + '%'}"></view>
							<view class="progress-dot" :style="{left: (video.progress || 0) + '%'}"></view>
						</view>
						<text class="progress-time" v-if="video.currentTime && video.duration">{{formatTime(video.currentTime)}} / {{formatTime(video.duration)}}</text>
					</view>
					
					<view class="action-buttons">
						<view class="action-item" @click="toggleLike(video)">
							<uni-icons :type="video.isLiked ? 'heart-filled' : 'heart'" size="30" :color="video.isLiked ? '#ff0000' : '#ffffff'"></uni-icons>
							<text class="action-count">{{video.likes}}</text>
						</view>
						<view class="action-item" @click="showCommentModal(video)">
							<uni-icons type="chat" size="30" color="#ffffff"></uni-icons>
							<text class="action-count">{{video.comments}}</text>
						</view>
						<view class="action-item" @click="showShareModal(video)">
							<uni-icons type="redo" size="30" color="#ffffff"></uni-icons>
							<text class="action-count">{{video.shares}}</text>
						</view>
					</view>
				</view>
			</swiper-item>
		</swiper>
		
		<!-- 评论组件 -->
		<douyin-comment 
			ref="commentComponent"
			:videoId="currentVideo ? currentVideo.id : ''"
			:initialComments="currentVideo ? currentVideo.commentList : []"
			:totalComments="currentVideo ? currentVideo.commentList.length : 0"
			:showEmptyPrompt="true"
			emptyPrompt="当前暂无评论，赶快去评论吧"
			@comment-added="handleCommentAdded"
			@comment-liked="handleCommentLiked"
			@reply-liked="handleReplyLiked"
			@load-more="handleLoadMoreComments"
			@load-more-replies="handleLoadMoreReplies"
			@close="onCommentClose"
		/>
		
		<!-- 分享弹窗 -->
		<uni-popup ref="sharePopup" type="bottom">
			<view class="share-popup">
				<view class="share-title">分享到</view>
				<view class="share-list">
					<view class="share-item" v-for="platform in sharePlatforms" :key="platform.id" @click="shareTo(platform.id.split('_')[1] || platform.id)">
						<text class="share-icon">{{platform.icon}}</text>
						<text>{{platform.name}}</text>
					</view>
				</view>
				<button class="share-cancel" @click="closeShareModal">取消</button>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import douyinComment from '@/components/comment/douyinComment.vue';
	import shareSDK from '@/utils/shareSDK.js';
	import memoryManager from '@/utils/memoryManager.js';
	
	export default {
		components: {
			douyinComment
		},
		data() {
			return {
				currentIndex: 0,
				currentVideo: null,
				commentsOpen: false,
				isDragging: false,
				startX: 0,
				startProgress: 0,
				videoList: [
					{
						id: '1',
						url: '/static/video/d4d4c86d3825e321b54a23696126bc44.mp4',//视频
						cover: '/static/video/1.jpg',//封面图
						avatar: '/static/logo.png',//头像
						username: '火隐忍者',//用户名
						description: '火隐忍者',//描述
						likes: 1000,//点赞数
						comments: 200,//评论数
						shares: 50,//分享数
						isLiked: false,//是否点赞
						isFollowed: false,
						type: '9:16',//视频比例
						loading: true,//是否加载
						canPlay: false,
						isPlaying: true,
						currentTime: 0,
						duration: 0,
						progress: 0,
						commentList: [
							{
								id: '101',
								avatar: '/static/logo.png',
								username: '用户A',
								content: '这个视频真不错！',
								time: '10分钟前',
								likes: 56,
								isLiked: false,
								replies: [
									{
										id: '1001',
										username: '用户B',
										content: '我也觉得很棒',
										time: '8分钟前',
										likes: 12,
										isLiked: false
									},
									{
										id: '1002',
										username: '用户C',
										content: '确实很有意思',
										time: '5分钟前',
										likes: 8,
										isLiked: false
									}
								],
								totalReplies: 2
							},
							{
								id: '102',
								avatar: '/static/logo.png',
								username: '用户D',
								content: '哈哈哈太有趣了',
								time: '30分钟前',
								likes: 45,
								isLiked: false,
								replies: [
									{
										id: '1003',
										username: '用户E',
										content: '笑死我了',
										time: '25分钟前',
										likes: 15,
										isLiked: false
									}
								],
								totalReplies: 1
							},
							{
								id: '103',
								avatar: '/static/logo.png',
								username: '用户F',
								content: '这个特效太厉害了',
								time: '1小时前',
								likes: 78,
								isLiked: false
							},
							{
								id: '104',
								avatar: '/static/logo.png',
								username: '用户G',
								content: '求背景音乐',
								time: '2小时前',
								likes: 32,
								isLiked: false,
								replies: [
									{
										id: '1004',
										username: '用户H',
										content: '同求',
										time: '1小时前',
										likes: 5,
										isLiked: false
									}
								],
								totalReplies: 1
							},
							{
								id: '105',
								avatar: '/static/logo.png',
								username: '用户I',
								content: '这个角度拍得真好',
								time: '3小时前',
								likes: 64,
								isLiked: false
							}
						]
					},
					{
						id: '2',
						url: '/static/video/d6c1a127997ea9f25e7630cb15462d59.mp4',
						cover: '/static/video/2.jpg',
						avatar: '/static/logo.png',
						username: '用户2',
						description: '分享美好生活 #日常',
						likes: 2000,
						comments: 300,
						shares: 100,
						isLiked: false,
						isFollowed: false,
						type: '16:9',
						loading: true,
						canPlay: false,
						isPlaying: true,
						currentTime: 0,
						duration: 0,
						progress: 0,
						commentList: [
							{
								id: '201',
								avatar: '/static/logo.png',
								username: '用户J',
								content: '拍得真好看',
								time: '2小时前',
								likes: 78,
								isLiked: false,
								replies: [
									{
										id: '2001',
										username: '用户K',
										content: '构图很棒',
										time: '1小时前',
										likes: 12,
										isLiked: false
									}
								],
								totalReplies: 1
							},
							{
								id: '202',
								avatar: '/static/logo.png',
								username: '用户L',
								content: '这是什么地方？',
								time: '3小时前',
								likes: 45,
								isLiked: false
							},
							{
								id: '203',
								avatar: '/static/logo.png',
								username: '用户M',
								content: '生活真美好',
								time: '4小时前',
								likes: 92,
								isLiked: false
							}
						]
					},
					{
						id: '3',
						url: '/static/video/46b84511148ad00c1de4b42d7abb0416.mp4',
						cover: '/static/video/3.jpg',
						avatar: '/static/logo.png',
						username: '用户3',
						description: '分享美好生活 #日常',
						likes: 2000,
						comments: 0,
						shares: 100,
						isLiked: false,
						isFollowed: false,
						type: '16:9',
						loading: true,
						canPlay: false,
						isPlaying: true,
						currentTime: 0,
						duration: 0,
						progress: 0,
						commentList: []
					}

				],
				showComment: false,
				showShare: false,
				commentList: [],
				commentPage: 1,
				commentLoading: false,
				commentFinished: false
			}
		},
		onLoad() {
			// 初始化内存管理器
			memoryManager.init(this);
		},
		onUnload() {
			// 清理资源
			memoryManager.cleanup();
		},
		computed: {
			// 计算实际评论总数（包括回复）
			actualCommentCount() {
				return this.videoList.reduce((total, video) => {
					const commentCount = video.commentList.length;
					const replyCount = video.commentList.reduce((sum, comment) => {
						return sum + (comment.replies ? comment.replies.length : 0);
					}, 0);
					return total + commentCount + replyCount;
				}, 0);
			},
			// 获取可用的分享平台
			sharePlatforms() {
				return shareSDK.getSupportedPlatforms();
			}
		},
		methods: {
			onSwiperChange(e) {
				const oldIndex = this.currentIndex;
				this.currentIndex = e.detail.current;
				
				// 暂停之前播放的视频
				if (oldIndex !== null && oldIndex !== this.currentIndex) {
					const oldVideoContext = uni.createVideoContext('video-' + oldIndex);
					memoryManager.removeVideoContext('video-' + oldIndex);
					oldVideoContext.pause();
				}
				
				// 播放当前视频
				const videoContext = uni.createVideoContext('video-' + this.currentIndex);
				memoryManager.addVideoContext('video-' + this.currentIndex, videoContext);
				videoContext.play();
			},
			togglePlay() {
				const videoContext = uni.createVideoContext('video-' + this.currentIndex);
				if (videoContext) {
					// 获取当前视频的播放状态
					const video = this.videoList[this.currentIndex];
					if (video.isPlaying) {
						videoContext.pause();
					} else {
						videoContext.play();
					}
					video.isPlaying = !video.isPlaying;
				}
			},
			toggleLike(video) {
				video.isLiked = !video.isLiked;
				video.likes += video.isLiked ? 1 : -1;
			},
			onVideoLoaded(e) {
				const index = parseInt(e.currentTarget.dataset.index);
				if (this.videoList[index]) {
					this.videoList[index].loading = false;
					this.videoList[index].canPlay = true;
				}
			},
			onVideoWaiting(e) {
				const index = parseInt(e.currentTarget.dataset.index);
				if (this.videoList[index]) {
					this.videoList[index].loading = true;
				}
			},
			onVideoError(e) {
				const index = parseInt(e.currentTarget.dataset.index);
				if (this.videoList[index]) {
					this.videoList[index].loading = false;
					this.videoList[index].canPlay = false;
				}
				// uni.showToast({
				// 	title: '视频加载失败',
				// 	icon: 'none'
				// });
			},
			showCommentModal(video) {
				this.currentVideo = video;
				this.commentsOpen = true;
				this.$refs.commentComponent.open();
			},
			onCommentClose() {
				this.currentVideo = null;
				this.commentsOpen = false;
			},
			handleCommentAdded(data) {
				if (this.currentVideo) {
					// 添加新评论到列表
					this.currentVideo.commentList.unshift({
						id: Date.now().toString(),
						avatar: '/static/logo.png',
						username: '当前用户',
						content: data.content,
						time: '刚刚',
						likes: 0,
						isLiked: false,
						replies: [],
						totalReplies: 0
					});
					// 更新评论总数
					this.currentVideo.comments = this.currentVideo.commentList.length;
				}
			},
			handleCommentLiked(data) {
				// 可以实现点赞相关的后端逻辑
				console.log('评论点赞', data);
			},
			handleReplyLiked(data) {
				// 可以实现回复点赞相关的后端逻辑
				console.log('回复点赞', data);
			},
			handleLoadMoreComments(data) {
				// 实现加载更多评论的逻辑
				console.log('加载更多评论', data);
			},
			handleLoadMoreReplies(data) {
				// 实现加载更多回复的逻辑
				console.log('加载更多回复', data);
			},
			showShareModal(video) {
				this.currentVideo = video;
				this.$refs.sharePopup.open();
			},
			closeShareModal() {
				this.$refs.sharePopup.close();
			},
			shareTo(platform) {
				const options = shareSDK.getShareOptionsFromVideo(this.currentVideo);
				
				// 调用分享SDK
				shareSDK.share(shareSDK.PLATFORMS[platform.toUpperCase()], options, (success, result) => {
					if (success) {
						this.currentVideo.shares++;
						uni.showToast({
							title: '分享成功',
							icon: 'success'
						});
					} else {
						console.error('分享失败:', result.error);
					}
				});
				
				this.closeShareModal();
			},
			onVideoPlay(e) {
				const index = parseInt(e.currentTarget.dataset.index);
				if (this.videoList[index]) {
					this.videoList[index].loading = false;
					this.videoList[index].canPlay = true;
				}
			},
			onVideoPause(e) {
				const index = e.currentTarget.dataset.index;
				const videoContext = uni.createVideoContext('video-' + index);
				memoryManager.removeVideoContext('video-' + index);
			},
			onVideoEnd(e) {
				const index = parseInt(e.currentTarget.dataset.index);
				const videoContext = uni.createVideoContext('video-' + index);
				memoryManager.removeVideoContext('video-' + index);
				
				// 视频播放完成后暂停
				videoContext.pause();
				this.videoList[index].isPlaying = false;
			},
			toggleFollow(video) {
				video.isFollowed = !video.isFollowed;
				uni.showToast({
					title: video.isFollowed ? '关注成功' : '已取消关注',
					icon: 'none'
				});
			},
			onVideoTimeUpdate(e) {
				const index = parseInt(e.currentTarget.dataset.index);
				if (this.videoList[index]) {
					const video = this.videoList[index];
					const currentTime = e.detail.currentTime;
					const duration = e.detail.duration;
					
					// 更新进度
					video.currentTime = currentTime;
					video.duration = duration;
					video.progress = (currentTime / duration) * 100;
				}
			},
			formatTime(seconds) {
				if (!seconds) return '00:00';
				
				seconds = Math.floor(seconds);
				const minutes = Math.floor(seconds / 60);
				seconds = seconds % 60;
				
				return `${minutes < 10 ? '0' + minutes : minutes}:${seconds < 10 ? '0' + seconds : seconds}`;
			},
			onProgressTouchStart(e) {
				this.isDragging = true;
				const touch = e.touches[0];
				const query = uni.createSelectorQuery().in(this);
				query.select('.progress-bar').boundingClientRect(data => {
					if (!data) return;
					this.startX = touch.clientX;
					this.startProgress = this.videoList[this.currentIndex].progress || 0;
					
					// 计算初始点击位置的进度
					const clickX = touch.clientX - data.left;
					const initialProgress = (clickX / data.width) * 100;
					this.startProgress = Math.max(0, Math.min(100, initialProgress));
					
					// 更新进度显示
					this.videoList[this.currentIndex].progress = this.startProgress;
				}).exec();
			},
			onProgressTouchMove(e) {
				if (!this.isDragging) return;
				
				const index = this.currentIndex;
				const video = this.videoList[index];
				if (!video || !video.duration) return;
				
				const touch = e.touches[0];
				const query = uni.createSelectorQuery().in(this);
				query.select('.progress-bar').boundingClientRect(data => {
					if (!data) return;
					
					// 计算移动距离
					const moveX = touch.clientX - data.left;
					const newProgress = (moveX / data.width) * 100;
					
					// 限制进度范围
					const clampedProgress = Math.max(0, Math.min(100, newProgress));
					
					// 更新进度显示
					video.progress = clampedProgress;
					
					// 计算新的播放时间
					const newTime = (video.duration * clampedProgress) / 100;
					video.currentTime = newTime;
				}).exec();
			},
			onProgressTouchEnd(e) {
				if (!this.isDragging) return;
				
				const index = this.currentIndex;
				const video = this.videoList[index];
				if (!video || !video.duration) return;
				
				// 更新视频播放位置
				const newTime = (video.duration * video.progress) / 100;
				const videoContext = uni.createVideoContext('video-' + index);
				videoContext.seek(newTime);
				
				this.isDragging = false;
			}
		}
	}
</script>

<style>
	.container {
		width: 100%;
		height: 100vh;
		background-color: #000;
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		overflow: hidden;
	}
	
	.video-swiper {
		width: 100%;
		height: 100%;
		transition: all 0.3s ease;
		will-change: transform;
	}
	
	.video-swiper.comments-open {
		height: 50vh;
		transform: translateY(0);
	}
	
	.video-container {
		width: 100%;
		height: 100%;
		position: relative;
		display: flex;
		justify-content: center;
		align-items: center;
		transform: translateZ(0);
		backface-visibility: hidden;
		perspective: 1000;
	}
	
	.video-wide {
		background-color: #000;
	}
	
	.video-tall {
		background-color: #000;
	}
	
	.video-player {
		width: 100%;
		height: 100%;
		object-fit: cover;
		transform: translateZ(0);
		backface-visibility: hidden;
		perspective: 1000;
	}
	
	.loading-container {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		z-index: 1;
	}
	
	.loading-circle {
		width: 40px;
		height: 40px;
		border: 3px solid rgba(255, 255, 255, 0.3);
		border-radius: 50%;
		border-top-color: #fff;
		animation: spin 1s linear infinite;
	}
	
	@keyframes spin {
		0% { transform: rotate(0deg); }
		100% { transform: rotate(360deg); }
	}
	
	.video-info {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 20px;
		background: linear-gradient(to top, rgba(0,0,0,0.8), transparent);
		color: #ffffff;
		z-index: 2;
	}
	
	.user-info {
		display: flex;
		align-items: center;
		margin-bottom: 15px;
	}
	
	.user-details {
		flex: 1;
		margin-right: 10px;
	}
	
	.avatar {
		width: 40px;
		height: 40px;
		border-radius: 50%;
		margin-right: 10px;
	}
	
	.username {
		font-size: 16px;
		font-weight: bold;
		display: block;
	}
	
	.description {
		font-size: 14px;
		margin-top: 5px;
		display: block;
	}
	
	.follow-btn {
		padding: 4px 12px;
		border-radius: 16px;
		background-color: rgba(255, 255, 255, 0.2);
	}
	
	.follow-text {
		font-size: 14px;
		color: #ffffff;
	}
	
	.follow-text.followed {
		color: #999;
	}
	
	.action-buttons {
		position: absolute;
		right: 20px;
		bottom: 100px;
		display: flex;
		flex-direction: column;
		align-items: center;
		z-index: 2;
	}
	
	.action-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 20px;
	}
	
	.action-count {
		color: #ffffff;
		font-size: 12px;
		margin-top: 5px;
	}
	
	/* 分享弹窗样式 */
	.share-popup {
		background-color: #fff;
		border-radius: 20rpx 20rpx 0 0;
		padding: 30rpx;
	}
	
	.share-title {
		text-align: center;
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 30rpx;
	}
	
	.share-list {
		display: flex;
		justify-content: space-around;
		margin-bottom: 30rpx;
	}
	
	.share-item {
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	
	.share-item text {
		font-size: 24rpx;
		color: #333;
		margin-top: 10rpx;
	}
	
	.share-icon {
		font-size: 60rpx;
		line-height: 80rpx;
		text-align: center;
		margin-bottom: 10rpx;
	}
	
	.share-cancel {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		background-color: #f5f5f5;
		color: #333;
		font-size: 28rpx;
		border-radius: 40rpx;
	}
	
	.no-video {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		z-index: 2;
	}
	
	.no-video-text {
		font-size: 32rpx;
		color: #ffffff;
		text-align: center;
	}
	
	/* 进度条样式 */
	.progress-container {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 10px 20px;
		background: linear-gradient(to top, rgba(0,0,0,0.8), transparent);
		z-index: 2;
	}
	
	.progress-bar {
		position: relative;
		height: 4px;
		background-color: rgba(255, 255, 255, 0.3);
		border-radius: 2px;
		overflow: visible;
		margin-bottom: 5px;
	}
	
	.progress-inner {
		position: absolute;
		height: 100%;
		background-color: #ff0000;
		border-radius: 2px;
		transition: width 0.1s linear;
	}
	
	.progress-dot {
		position: absolute;
		width: 12px;
		height: 12px;
		background-color: #ff0000;
		border-radius: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		box-shadow: 0 0 4px rgba(0,0,0,0.3);
		transition: left 0.1s linear;
	}
	
	.progress-time {
		font-size: 12px;
		color: rgba(255, 255, 255, 0.8);
		display: block;
		text-align: right;
	}
</style>
